import React, { useState } from 'react';
import { Form, Input, Button, Select, Space } from 'antd';
import { rabiaFirstLogin, rabiaLogin, rabiaGetAccountBaseInfo } from '@/services/base-layout-service';
import { setStorage, clearStorage, getRealMenuList } from '@/biz';
import { uiData } from '@/store';
import { useNavigate } from 'react-router';
import { getFrontCodeListForAdmin } from '@/biz';
import { permsMap } from '@config/perms/perms-config';
import { md5 } from '@/utils';

interface IAccountItem {
    accountId: string;
    accountName: string;
    orgId: string;
    orgName: string;
    userId: string;
}

export const getFirstPagePath = (menuList) => {
    const getPathFromArr = (list) => {
        let targetPath = '';
        if (Array.isArray(list)) {
            list.sort((a, b) => {
                return a.orderNum - b.orderNum;
            });
            for (let i = 0, len = list.length; i < len; i++) {
                const item = list[i];
                if (permsMap[item.perms]?.path) {
                    targetPath = permsMap[item.perms]?.path;
                    return targetPath;
                }
                if (item.children) {
                    return getPathFromArr(item.children);
                }
            }
        }
        return targetPath;
    };
    return getPathFromArr(menuList);
};

const RightRabiaLogin = () => {
    const [form] = Form.useForm();
    const [accountList, setAccountList] = useState<IAccountItem[]>();
    const [loginToken, setLoginToken] = useState<string>();
    const navigate = useNavigate();

    // 登录成功
    const handleLoginSuccess = async (loginData) => {
        try {
            clearStorage();
            setStorage({ token: loginData?.token.accessToken });
            const { userInfo, frontCodeList, menuList: originMenuList, roleList } = await rabiaGetAccountBaseInfo({});
            const _frontCodeList = userInfo?.adminFlag ? getFrontCodeListForAdmin() : frontCodeList;
            const realMenuList = getRealMenuList(_frontCodeList, originMenuList);
            setStorage({ userInfo, frontCodeList: _frontCodeList, originMenuList, menuList: realMenuList, roleList });
            uiData.updateFrontCodeList(_frontCodeList);
            const targetPath = getFirstPagePath(realMenuList);
            navigate(targetPath || '/auth');
        } catch (error) {
            console.error(`login error - ${JSON.stringify(error)}----${error}`);
        }
    };

    // 表单提交
    const handleFinish = async (values) => {
        const password = md5(values?.password);
        if (values?.accountId) {
            try {
                // 第二步选择组织后登录
                const userId = accountList?.find((i) => i?.accountId === values?.accountId)?.userId;
                const params = { ...values, password, userId, loginToken };
                const res = await rabiaLogin(params);
                if (res) {
                    handleLoginSuccess(res);
                }
            } catch (error) {
                console.error(error);
                clearData();
            }
        } else {
            // 第一步获取组织列表
            const params = { ...values, password };
            const res = (await rabiaFirstLogin(params)) as { accountList: IAccountItem[]; loginToken: string };
            if (res) {
                setAccountList(res?.accountList);
                setLoginToken(res?.loginToken);
                form.setFieldsValue({ accountId: res?.accountList[0]?.accountId });
            }
        }
    };

    const clearData = () => {
        form.resetFields();
        setAccountList(null);
        setLoginToken(null);
    };

    return (
        <div>
            <h1>登录</h1>
            <Form form={form} wrapperCol={{ span: 12 }} onFinish={handleFinish} layout="vertical">
                <Form.Item name="userName" label="用户名" rules={[{ required: true }]}>
                    <Input disabled={Boolean(loginToken)} />
                </Form.Item>
                <Form.Item name="password" label="密码" rules={[{ required: true }]}>
                    <Input.Password disabled={Boolean(loginToken)} />
                </Form.Item>
                {loginToken ? (
                    <Form.Item name="accountId" label="组织" rules={[{ required: true }]}>
                        <Select options={accountList?.map((item) => ({ value: item?.accountId, label: item?.orgName }))} />
                    </Form.Item>
                ) : null}
                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit">
                            {accountList ? '登录' : '获取组织列表'}
                        </Button>
                        {accountList ? <Button onClick={clearData}>更换用户</Button> : null}
                    </Space>
                </Form.Item>
            </Form>
        </div>
    );
};

export default RightRabiaLogin;
